//
//  HTDeliverDetialVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/30.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTDeliverDetialVC.h"
#import "HTDeliverDriverCell.h"
#import "HTDetialMapLineVC.h"
#import "HTDriverMainVC.h"
#import "HTDeliverDetialHomeModel.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MapKit/MapKit.h>


@interface HTDeliverDetialVC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
@property (weak, nonatomic) IBOutlet UILabel *truckTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *remarkFirstLabel;
@property (weak, nonatomic) IBOutlet UILabel *remarkSecondLabel;

@property (weak, nonatomic) IBOutlet UILabel *checkLineLabel;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *detialAddressLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *checkImageView;


@property (weak, nonatomic) IBOutlet UIView *rightView;
@property (weak, nonatomic) IBOutlet UIView *leftView;
@property (weak, nonatomic) IBOutlet UILabel *acceptPhoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *sawPhoneLabel;
@property (weak, nonatomic) IBOutlet UIView *rightLineView;
@property (weak, nonatomic) IBOutlet UIView *rightLongLine;
@property (weak, nonatomic) IBOutlet UIView *leftLongLine;
@property (weak, nonatomic) IBOutlet UIView *leftLineView;

@property (nonatomic,assign) NSInteger index;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSMutableArray *viewData;
@property (nonatomic,strong) NSMutableArray *callData;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;
@property (weak, nonatomic) IBOutlet UIButton *closeButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;

@property (nonatomic,strong) HTDeliverDetialHomeModel *deliverDetialHomeModel;

@end

@implementation HTDeliverDetialVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    if (_isClosed) {
        self.bottomHeight.constant = 0;
        self.closeButton.hidden = YES;
    }
    [self setupInit];
    [self setupData];
    [self netLoadData];
    [self distanceValue];
    
}
- (void)setupData{
    self.startLabel.text = self.deliverGoodsModel.fromadd;
    self.endLabel.text = self.deliverGoodsModel.toadd;
    NSString *length = [HTUtils sortLengthDisplayStringWith:self.deliverGoodsModel.heiht];
    NSString *type = @"不限车型";
    if (!(self.deliverGoodsModel.type == nil || self.deliverGoodsModel.type.length <= 0)) {
        type = self.deliverGoodsModel.type;
    }
    NSString *dun = @"";
    if ([self.deliverGoodsModel.utit isEqualToString:@"1"]) {
        dun =[NSString stringWithFormat:@"%@吨",self.deliverGoodsModel.weight];
    }else{
        dun =[NSString stringWithFormat:@"%@方",self.deliverGoodsModel.weight];
    }
    NSString *cartype = @"";
    if (!(self.deliverGoodsModel.cartype == nil || self.deliverGoodsModel.cartype.length <= 0)) {
        cartype = self.deliverGoodsModel.cartype;
    }
    self.truckTypeLabel.text = [NSString stringWithFormat:@"%@ %@ / %@ %@ / 运费%@元",length,type,dun,cartype,self.deliverGoodsModel.pricers];
    self.detialAddressLabel.text = [HTUtils timeIntervalExchange:self.deliverGoodsModel.createtime];
   
}
- (void)reloadTableView{
    if (self.dataSource.count <= 0) {
        self.tableView.hidden = YES;
    }else{
        self.tableView.hidden = NO;
    }
    [self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTDeliverDriverCell *delivercell = [tableView dequeueReusableCellWithIdentifier:deliverDriverCell forIndexPath:indexPath];
    delivercell.deliverDetialModel = self.dataSource[indexPath.row];
    return delivercell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HTDriverMainVC *driverMain = [[HTDriverMainVC alloc]init];
    driverMain.ID = [self.dataSource[indexPath.row] driverid];
    [self.navigationController pushViewController:driverMain animated:YES];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (void)setupInit{
    self.title = @"货源详情";
    self.index = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCheckLine)];
    self.checkImageView.userInteractionEnabled = YES;
    [self.checkImageView addGestureRecognizer:tap];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didSelectedTap:)];
     UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didSelectedTap:)];
    self.leftView.tag = 171;
    self.rightView.tag = 172;
    [self.leftView addGestureRecognizer:tap1];
    [self.rightView addGestureRecognizer:tap2];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTDeliverDriverCell" bundle:nil] forCellReuseIdentifier:deliverDriverCell];
    
}
- (void)didCheckLine{
    HTDetialMapLineVC *detial = [[HTDetialMapLineVC alloc]init];
    detial.startName = self.deliverGoodsModel.fromadd;
    detial.endName = self.deliverGoodsModel.toadd;
    [self.navigationController pushViewController:detial animated:YES];
}
- (void)didSelectedTap:(UITapGestureRecognizer *)sender{
    if (sender.view.tag == 171) {
        if (self.index == 0) {
            return;
        }
        self.index = 0;
        [self reloadTableView];
    }else{
        if (self.index == 1) {
            return;
        }
        self.index = 1;
        [self reloadTableView];
    }
}
- (void)setIndex:(NSInteger)index{
    _index = index;
    if (index == 0) {
        [self selectedLeft];
        self.dataSource = self.callData;
    }else{
        [self selectRight];
        self.dataSource = self.viewData;
    }
}
- (void)selectedLeft{
    self.leftLineView.hidden = NO;
    self.rightLineView.hidden = YES;
    self.leftLongLine.hidden = YES;
    self.rightLongLine.hidden = NO;
    self.acceptPhoneLabel.textColor = kBlueColor;
    self.sawPhoneLabel.textColor = [UIColor darkGrayColor];
}
- (void)selectRight{
    self.leftLineView.hidden = YES;
    self.rightLineView.hidden = NO;
    self.leftLongLine.hidden = NO;
    self.rightLongLine.hidden = YES;
    self.acceptPhoneLabel.textColor = [UIColor darkGrayColor];
    self.sawPhoneLabel.textColor = kBlueColor;
}

#pragma mark --- 网络请求
- (void)netLoadData{
    [self startHud];
    [HTHttpRequestManager requestDeliverHolderInfoWithProductid:self.deliverGoodsModel.orderid success:^(id  _Nullable responseObject) {
         [self endHud];
        DBLog(@"货源信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"货源信息请求失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        
        self.deliverDetialHomeModel = [HTDeliverDetialHomeModel   mj_objectWithKeyValues:responseObject[@"data"]];
        self.callData = [HTDeliverDetialModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"calldata"][@"data"]];
        self.viewData = [HTDeliverDetialModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"viewdata"][@"data"]];
        self.index = 0;
        [self reloadTableView];
        
    } failure:^(NSError * _Nonnull error) {
         [self endHud];
    }];
    
}
- (void)setDeliverDetialHomeModel:(HTDeliverDetialHomeModel *)deliverDetialHomeModel{
    _deliverDetialHomeModel = deliverDetialHomeModel;
    NSString *time = (deliverDetialHomeModel.strattime == nil || deliverDetialHomeModel.strattime.length <= 0)?@"":[NSString stringWithFormat:@"装车时间 %@ ",deliverDetialHomeModel.strattime];
    NSString *addtype = (deliverDetialHomeModel.addtype == nil || deliverDetialHomeModel.addtype.length <= 0)?@"":deliverDetialHomeModel.addtype;
    NSString *paytype = (deliverDetialHomeModel.paytype == nil || deliverDetialHomeModel.paytype.length <= 0)?@"":[NSString stringWithFormat:@"%@ ",deliverDetialHomeModel.paytype];
    NSString *remark =  (deliverDetialHomeModel.remark == nil || deliverDetialHomeModel.remark.length <= 0)?@"":[NSString stringWithFormat:@"%@ ",deliverDetialHomeModel.remark];
    self.remarkFirstLabel.text = [NSString stringWithFormat:@"%@%@",time,addtype];
    self.remarkSecondLabel.text = [NSString stringWithFormat:@"%@%@",paytype,remark];
    self.startLabel.text = deliverDetialHomeModel.from;
    self.endLabel.text = deliverDetialHomeModel.to;
    NSString *length = [HTUtils sortLengthDisplayStringWith:deliverDetialHomeModel.length];
    NSString *type = @"不限车型";
    if (!(deliverDetialHomeModel.lengthtype == nil || deliverDetialHomeModel.lengthtype.length <= 0)) {
        type = deliverDetialHomeModel.lengthtype;
    }
    NSString *dun = @"";
    if ([deliverDetialHomeModel.utit isEqualToString:@"1"]) {
        dun =[NSString stringWithFormat:@"%@吨",deliverDetialHomeModel.weight];
    }else{
        dun =[NSString stringWithFormat:@"%@方",deliverDetialHomeModel.weight];
    }
    NSString *cartype = @"";
    if (!(deliverDetialHomeModel.goodstype == nil || deliverDetialHomeModel.goodstype.length <= 0)) {
        cartype = deliverDetialHomeModel.goodstype;
    }
    self.truckTypeLabel.text = [NSString stringWithFormat:@"%@ %@ / %@ %@ / 运费%@元",length,type,dun,cartype,deliverDetialHomeModel.pricer];
    self.detialAddressLabel.text = [HTUtils timeIntervalExchange:deliverDetialHomeModel.createtime];
}
- (IBAction)didCloseButton:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"货源已关闭"]) {
        [HTShowUtil showMessage:@"货源已关闭"];
        return;
    }
    [self netLoadDataClose];
}
- (void)netLoadDataClose{
    
    [self netLoadDataWithState:@"1"];
}
- (void)netLoadDataDeliver{
    [self netLoadDataWithState:@"0"];
}
- (void)netLoadDataWithState:(NSString *)state{
    [self startHud];
    [HTHttpRequestManager requestDeliverStateChangeWithProduceid:self.deliverGoodsModel.orderid state:state success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"货源关闭失败：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"货源关闭失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        [HTShowUtil showMessage:responseObject[@"message"]];
        if ([state isEqualToString:@"1"]) {
             [self.closeButton setTitle:@"货源已关闭" forState:UIControlStateNormal];
        }else{
             [self.closeButton setTitle:@"关闭货源" forState:UIControlStateNormal];
        }
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
    }];
}



//计算直线距离
- (void)distanceValue{
    
    CLGeocoder *geoC = [[CLGeocoder alloc] init];
    
    [geoC geocodeAddressString:self.deliverGoodsModel.fromadd completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        if(error == nil)
        {
            CLLocationCoordinate2D startCoordinate = pl.location.coordinate;
            [geoC geocodeAddressString:self.deliverGoodsModel.toadd completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                CLPlacemark *pl = [placemarks firstObject];
                
                if(error == nil)
                {
                    CLLocationCoordinate2D destinationCoordinate = pl.location.coordinate;
                    MKMapPoint point1  = MKMapPointForCoordinate(startCoordinate);
                    MKMapPoint point2  = MKMapPointForCoordinate(destinationCoordinate);
                    CLLocationDistance distance = MKMetersBetweenMapPoints(point1,point2);
                    self.distanceLabel.text = [NSString stringWithFormat:@"%.1f",distance/1000];
                }
            }];
        }
    }];
}
@end
